<template>
  <a-modal title="设置" :after-close="reset" @ok="submit">
    <a-form ref="formRef" :model="form" :rules="rules" :label-col="{ style: { width: '80px' } }">
      <a-form-item v-if="props.type == 'group'" label="用户分组：">
        <a-select v-model:value="form.groupId" placeholder="请选择" clearable filterable>
          <a-select-option v-for="(item, index) in groupList" :key="index" :value="item.id">
            {{ item.groupName }}
          </a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item v-else label="用户标签：">
        <a-select v-model:value="form.groupId" placeholder="请选择" clearable filterable>
          <a-select-option v-for="(item, index) in labelList" :key="index" :value="item.id">
            {{ item.name }}
          </a-select-option>
        </a-select>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import { tagPiApi, groupPiApi } from "./api";
import { user, type Iuser } from './entity';
import { validReg } from '@/utils/validate';
import type { Iusergroup } from "./group/entity";
import type { Iusertag } from "./label/entity";

const props = withDefaults(defineProps<{
  data: Partial<Iuser>
  groupList: Iusergroup[],
  labelList: Iusertag[],
  type: string
}>(), {
})
const { formRef, submit, close } = useDialog({ validCallback: save })

let form = $ref(new user())
watchEffect(() => {
  if (props.data) {
    form.id = props.data.uid

  }
})

const rules = {
  usergroupName: [validReg('required', '请输入用户名')]
}

onMounted(() => {
})

const emit = defineEmits(['change'])

async function save() {
  let { id, groupId } = form
  if (props.type == 'group') {
    await groupPiApi({ id, groupId })
  } else {
    await tagPiApi({ id, tagId: groupId })
  }
  await nextTick()
  AntMessage.success('保存成功')
  close()
  emit('change')
}

function reset() {
  form = new user()
}
</script>

<style lang="less"></style>
